package com.modular.system.captcha;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tool.ToolRedisson;
import ntd.util.cache.FactoryCache;
import ntd.util.config.common.bo.ResponseBO;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.task.handle.fm.util.UtilFmMsg;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    private static final String CAPTCHA_CODE_KEY = "CAPTCHA-";

    @GetMapping("phone/code")
    public ResponseBO<String> phoneCode(String phone) {
        if (StrUtil.isBlank(phone)) {
            throw new ComException("手机号不能为空！");
        }

        if (!PhoneUtil.isPhone(phone)) {
            throw new ComException("手机号不合法！");
        }
        String code = ToolRedisson.me.get("captcha:" + phone, () -> RandomUtil.randomNumbers(6), Duration.ofSeconds(60 * 5));

        UtilFmMsg.captcha(phone, code);

        return new ResponseBO<>(code);
    }

    @GetMapping("verify")
    public  ResponseBO<Boolean> verify(String phone, String code) {
        if (!StrUtil.isAllNotBlank(phone, code)) {
            throw new ComException("缺少必要参数......");
        }

        if (!PhoneUtil.isPhone(phone)) {
            throw new ComException("手机号不合法！");
        }
        String verifyCode = ToolRedisson.me.get("captcha:" + phone);
        if (StrUtil.equals(verifyCode, code)) {
            return new ResponseBO<>(true);
        }
        return new ResponseBO<>(false);
    }

    @GetMapping("img/code")
    public ResponseBO<JSONObject> getCode() {
        // 保存验证码信息
        String verifyKey = CAPTCHA_CODE_KEY + IdUtil.simpleUUID().toUpperCase();

        // 生成验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100);

        JSONObject json = JSONUtil.createObj();
        json.putOpt("code", verifyKey);
        json.putOpt("img", Base64.encode(circleCaptcha.getImageBytes()));

        FactoryCache.cache(verifyKey).cache(circleCaptcha.getCode());

        return new ResponseBO(json);
    }

}
